package com.audaque.springboot.foshanupload.core.serializer;

import com.audaque.springboot.foshanupload.core.enums.DataMask;
import com.audaque.springboot.foshanupload.core.inface.DataMaskFunction;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zgb
 * @desc 数据脱密序列化对象
 * @date 2022-11-22 20:16:04
 */

public final class DataMaskSerializer extends StdScalarSerializer<Object> {
    private final DataMaskFunction dataMaskFunction;

    public DataMaskSerializer() {
        super(String.class, false);
        this.dataMaskFunction = null;
    }

    public DataMaskSerializer(DataMaskFunction dataMaskFunction) {
        super(String.class, false);
        this.dataMaskFunction = dataMaskFunction;
    }


    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws  IOException {
        if (Objects.isNull(dataMaskFunction)) {
            //注解没有值，默认ALL_MASK
            String content = DataMask.ALL_MASK.getDataMaskFunction().mask((String) value, null);
            gen.writeString(content);
        } else {
            String content = dataMaskFunction.mask((String) value, null);
            gen.writeString(content);
        }
    }

}
